<template>
  <div class="translation merak-container-has-aside" curPageName="sfsadf23424534525234322">
    <div class="merak-card merak-container-has-search">
      <!-- 搜索模块儿 -->
      <div>
        <searchBar
          close-plan="true"
          ref="searchbar"
          :placeholder="$t('marking_excel.sku')+'/'+$t('marking_application_form.spu')"
          close-advanced
		  :close-enter="isShow"
          :search_val="search_val"
          @search-event="searchBarPost"
          v-model="searchform"
        >
          <!-- 高级搜索弹出框 插槽-->
          <template #searchForm="searchProp">
            <!--  高级搜索弹出框内容-->
            <div class="modal-content">
              <!-- 高级搜索 -->
              <div class="modal-title"></div>

              <div class="modal—body">
                <el-scrollbar class="search_from_scrollbar" height="100%">
                  <div class="scrollbar-content">
                    <!-- 已选参数 组件-->
                    <div class="r89768"></div>
                    <!-- 表单 -->
                    <el-form :model="searchform" :rules="searchformRules" label-position="top" ref="searchFormRef">
                      <el-row :gutter="40">
                        <el-col :span="8">
                          <el-form-item :label="$t('manage_record.employee_name')" prop="employee_name.value">
                            <el-input class="qf_input" v-model="searchform.employee_name.value" />
                          </el-form-item>
                        </el-col>
                        <el-col :span="8">
                          <el-form-item :label="$t('manage_record.job_number')">
                            <el-input class="qf_input" v-model="searchform.job_number.value" />
                          </el-form-item>
                        </el-col>
                        <el-col :span="8">
                          <el-form-item :label="$t('manage_record.rangetime')">
                            <el-date-picker
                              v-model="rangeTime"
                              type="daterange"
                              :start-placeholder="$t('leaves_record_list.begin')"
                              :end-placeholder="$t('leaves_record_list.end')"
                              class="qf_date"
                              @change="dataPost"
                              :format="format"
                              value-format="YYYY-MM-DD"
                            />
                          </el-form-item>
                        </el-col>
                        <el-col :span="8">
                          <el-form-item :label="$t('manage_record.type')">
                            <el-select
                              class="qf_select"
                              v-model="searchform.type.value"
                              :placeholder="$t('merak.placeholder_select')"
                            >
                              <el-option
                                v-for="item in searchform.type.options"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                              />
                            </el-select>
                          </el-form-item>
                        </el-col>
                      </el-row>
                    </el-form>
                    <!-- 表单 -->
                  </div>
                </el-scrollbar>
              </div>
              <div class="modal-footer">
                <!-- 取消 -->
                <el-button type="default" @click="closeModal(searchFormRef)">{{ $t("merak.reset") }}</el-button>
                <!-- 搜索 -->
                <el-button type="primary" @click="submitForm(searchFormRef)">{{ $t("merak.search") }}</el-button>
                <!-- 保存搜索方案 -->
                <el-button plain type="primary" v-if="searchProp.closePlan" @click="showPlanModal">
                  {{ $t("merak.save_search_scheme") }}
                </el-button>
              </div>
            </div>
            <!--  高级搜索弹出框内容-->
          </template>
          <!-- /高级搜索弹出框 插槽-->
          <template #header>
            <div class="search_header_slot">
              <el-select
                v-model="selectedValue"
                remote
                :filter-method="filterMethod"
                @change="fliterChange"
                filterable
                clearable
                :placeholder="$t('sys_log.user_name')"
                style="width: 180px"
              >
                <el-option v-for="item in filterResultOption" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
              <el-date-picker
                v-model="rangeTime"
                type="daterange"
                :start-placeholder="msg.beginDate"
                :end-placeholder="msg.endDate"
                @change="dataPost"
                :format="format"
                value-format="YYYY-MM-DD"
                class="sys_log_date"
              />
            </div>
          </template>
        </searchBar>
      </div>
      <div class="merak-table-wrapper">
        <MerakXTable
          ref="tableRef"
          :columns-by-store="JSON.parse(JSON.stringify(state.columns))"
          :query-columns="handleQueryColumns"
          :query-data="handleQueryData"
          :params="state.params"
          :column-type="columnTypeAuth"
          :batches="[]"
          :batch-click="handleBatchClick"
        >
          <template #handler="{ row }">
            <div>
              <!-- // 权限04 -->
              <el-button type="primary" link @click="drawerShow(row)"> {{ $t("sys_log.view") }} </el-button>
            </div>
          </template>

          <template #actionslots="{ row }">
            <el-tag v-if="row.type == 'insert'" type="success">新增</el-tag>
            <el-tag v-if="row.type == 'update'" type="info">编辑</el-tag>

            <el-tag v-if="row.type == 'delete'" type="danger">删除</el-tag>
          </template>
        </MerakXTable>
      </div>
    </div>

    <el-drawer modal-class="merak_modal manage_drawer" v-model="drawerSysDetail" direction="rtl" size="50%">
      <template #header>
        <div class="merak_modal_title">{{ $t("sys_log.logDetail") }}</div>
      </template>
      <div class="merak_modal_content">
        <div v-loading="loadDataStatus"></div>
        <div class="base_info">
          <ul>
            <li class="operator">{{ $t("sys_log.operator") }}: {{ recordDetail?.userInfo?.name }}</li>
            <li class="job_id">{{ $t("sys_log.jobId") }}: {{ recordDetail?.userInfo?.jobId }}</li>
            <li class="operation_method">{{ $t("sys_log.operationMethod") }}: {{ recordDetail?.userInfo?.operation }}</li>
            <!-- <li class="operation_method">操作时间：{{ recordDetail?.userInfo?.time }}</li> -->
            <li class="web_url">{{ $t("sys_log.pagePath") }}: {{ recordDetail?.userInfo?.webUrl }}</li>
          </ul>
        </div>
        <div class="record_base_info"></div>
        <el-divider />
        <div class="record">
          <el-scrollbar height="100%" always>
            <el-timeline class="timeline" style="max-width: 800px">
              <el-timeline-item v-for="(item, index) in recordDetail.records" :key="index" :timestamp="item?.operationTime">
                <template #dot>
                  <div v-if="item.action == 'insert'" class="action-icon action-icon-plus">
                    <el-icon size="11"><Plus /></el-icon>
                  </div>

                  <div v-if="item.action == 'delete'" class="action-icon action-icon-delete">
                    <el-icon size="11"><Close /></el-icon>
                  </div>

                  <div v-if="item.action == 'update'" class="action-icon action-icon-update">
                    <el-icon size="11"><Refresh /></el-icon>
                  </div>
                </template>
                {{ preProcessData(item) }}
                <!-- <template v-html="preProcessData(item)">

               </template> -->
              </el-timeline-item>
            </el-timeline>
          </el-scrollbar>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script lang="ts" setup name="logSRecord">
import router from "@/routers";
import { Plus, Edit, Delete, EditPen } from "@element-plus/icons-vue";

import { ref, reactive, onMounted, getCurrentInstance, registerRuntimeCompiler } from "vue";
import { useSysLogInit, useDrawerSysDetail, useLoading, useGetRecordFn } from "./index.ts";
import { ResultEnum } from "@/enums/httpEnum";
import searchBar from "@/components/SearchBar";
import merakColapse from "@/components/merakColapse/index.vue";
import selectedParams from "@/components/SearchBar/components/selectedParams.vue";

import MerakXTable, { MerakXTableInstance, MerakXTableColumn, MerakXTableQuery } from "@/components/MerakXTable";
import {
  moreConfirm,
  confirmWarningMsg,
  successMsg,
  warnMsg,
  failMsg,
  confirmSuccessMsg,
  delConfimMsg
} from "@/utils/messageUtils";
import { getSysLogHeader, getSysLogList, saveCreateSet, saveEditSet, delSet } from "@/api/modules/personalManagementApi/holiday";
import I18n from "@/languages/index";

import type { ElForm } from "element-plus";
import { pa } from "element-plus/es/locale";
type FormInstance = InstanceType<typeof ElForm>;
const setRef = ref<FormInstance>();
const logType = ref("");
const { proxy } = getCurrentInstance();
const msg = reactive({
  beginDate: proxy.$t("sys_log.beginDate"),
  endDate: proxy.$t("sys_log.endDate")
});
const showRemainingData = [
  {
    update_at: "sfsadfasd",
    days: "sdfsd",
    action: "sfgggg"
  }
];

const tableRef = ref<MerakXTableInstance>();

const color = ref("rgba(255, 69, 0, 0.68)");
const predefineColors = ref(["#E63415", "#FF6600", "#FFDE0A", "#1EC79D", "#14CCCC", "#4167F0", "#6222C9"]);

//批量操作
const handleBatchClick = async e => {
  console.log(e);
};

//#region 搜索表单
let search_val = ref("");
//#endregion

//#region  同步翻译 publishJs
const simultaneousTrans = () => {
  publishJs().then(res => {
    if (res.code == ResultEnum.SUCCESS) {
      successMsg("同步成功!请重新加载。");
    }
  });
};

//#endregion

//#region 新增、编辑、删除
// const drawerTranslation = ref(false);
const translationTitle = ref("新增假期");
//表单参数结构
const setForm = ref({
  user_leaves_set_id: 0,
  title: "",
  title_ru: "",
  remarks: "",
  remarks_ru: "",
  days: "",
  color: "#E63415"
});
const validateDay = (rule: any, value: any, callback: any) => {
  if (value === "") {
    callback(new Error(proxy.$t("main.requiredMsg")));
  } else {
    let reg = /^-?(0|([1-9][0-9]*))(\.[\d]+)?$/;
    if (reg.test(value)) {
    } else {
      callback(new Error("必须数字"));
    }
    callback();
  }
};
const translationRules = reactive({
  title: [{ required: true, message: proxy.$t("main.requiredMsg"), trigger: "change" }],
  title_ru: [{ required: true, message: proxy.$t("main.requiredMsg"), trigger: "change" }],
  remarks: [{ required: true, message: proxy.$t("main.requiredMsg"), trigger: "change" }],
  remarks_ru: [{ required: true, message: proxy.$t("main.requiredMsg"), trigger: "change" }],
  days: [{ required: true, validator: validateDay, trigger: "change" }]
});

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};
//新增操作
const onPlus = () => {
  setForm.value = {
    user_leaves_set_id: 0,
    title: "",
    title_ru: "",
    remarks: "",
    remarks_ru: "",
    days: "",
    color: "#E63415"
  };

  resetForm(setRef.value);
  //打开弹窗
  // drawerTranslation.value = true;
};

//新增
/**
 * typebtn 1保存 2保存并继续
 */
const postAdd = (typebtn: string, formEl: FormInstance | undefined) => {
  if (editShow.value) {
    //新增
    saveCreateSet(setForm.value).then(
      res => {
        console.log(res);
        if (res.code == ResultEnum.SUCCESS) {
          successMsg("保存成功!");
          if (typebtn == 1) {
            //关闭弹窗
            // drawerTranslation.value = false;
            //formEl.resetFields();
          } else {
            let resetObj = {
              user_leaves_set_id: 0,
              title: "",
              title_ru: "",
              remarks: "",
              remarks_ru: "",
              days: "",
              color: "#E63415"
            };
            setForm.value = { ...setForm.value, ...resetObj };

            resetForm(setRef.value);
          }

          tableRef.value?.reloadData();
        } else {
          failMsg(res.message);
        }
      },
      err => {
        console.log(err);
      }
    );
  } else {
    //编辑
    saveEditSet(setForm.value).then(
      res => {
        if (res.code == ResultEnum.SUCCESS) {
          successMsg("编辑成功!");
          //关闭弹窗
          // drawerTranslation.value = false;
          // formEl.resetFields();
          tableRef.value?.reloadData();
        } else {
          failMsg(res.message);
        }
      },
      err => {
        console.log(err);
      }
    );
  }
};

//编辑
let editShow = ref(true);
const saveEdit = (row: setForm) => {
  const rowt = JSON.parse(JSON.stringify(row));
  setForm.value = rowt;
  //打开弹窗
  // drawerTranslation.value = true;
  editShow.value = false;
};

//取消
const cancelEmpty = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  // drawerTranslation.value = false;
};

//删除
const delTranslation = (row: setForm) => {
  delConfimMsg({
    callback: val => {
      if (val == "confirm") {
        delOne(row);
      }
    }
  });
};

const delOne = (row: setForm) => {
  delSet({ user_leaves_set_id: row.user_leaves_set_id }).then(res => {
    successMsg("删除成功!");
    setTimeout(() => {
      tableRef.value?.reloadData();
    }, 500);
  });
};
//#endregion

const state = reactive<{
  params: Record<string, any>;
  columns: MerakXTableColumn[];
}>({
  params: {
    key_words: ""
  },
  columns: []
});

//权限01数据
let authArr = ref({});
let isShow = ref(true);
const $t = I18n.global.t;

const columnTypeAuth = reactive([]);

if ($t("lang") == "ru") {
  Object.assign(columnTypeAuth, [{ type: "handle", width: 280, slot: "handler" }]);
} else {
  Object.assign(columnTypeAuth, [{ type: "handle", width: 120, slot: "handler" }]);
}

//列表内容展示区
const handleQueryData: MerakXTableInstance["queryData"] = async ({ page, sorts, filters, from }) => {
  const params: Record<string, any> = {};
  if (!!page) {
    Object.assign(params, { ...page }, from);
  }
 await getRouterParams(router).then(res => {
    let path = res.currentRoute.value.path;
    logType.value = path.split("/")[2];
	console.log(logType.value)
	if(logType.value == "log_hr"){
		isShow.value = true
	} else {
		isShow.value = false
	}
    Object.assign(params, { logType: logType.value });
  }); 
  return await getSysLogList(params).then(res => { 
    if (res.code == ResultEnum.SUCCESS) {
      let data = res.data;

      for (let index = 0; index < data.table_data.list.length; index++) {
        const element = data.table_data.list[index];
        if (element.type == "insert" || element.type == "delete") {
          var newShow = [];

          for (const key in element.new) {
            var newObj = {};
            newObj["label"] = key;
            newObj["value"] = element.new[key];
            newShow.push(newObj);
          }

          element["tablexqShow"] = newShow;
        }
      }

      console.log(data.table_data);

      const { table_data, language } = data as { table_data: Record<string, any>; language: Record<string, any> };

      return table_data;
    }
  });
};

//表头信息
const handleQueryColumns: MerakXTableInstance["queryColumns"] = async () => {
  return await getSysLogHeader().then(res => {
    if (res.code == ResultEnum.SUCCESS) {
      let data = res.data as MerakXTableQuery.Columns;
      // const { pageSize, columns } = data as { pageSize: number; columns: MerakXTableColumn[] };
      console.log(data.columns);

      for (let index = 0; index < data.columns.length; index++) {
        const element = data.columns[index];
        if (element.field == "type") {
          element["slots"] = { default: `actionslots` };
        }
      }

      state.columns = data.columns;

      return data;
    }
  });
};

// 获取高级搜索方案
const queryFilterOptions = async data => {
  searchbar.value.getPlanList(data.table_id);
  // 初始化接口需要传入队列 loading 暴露的 id
};

const dataPost = params => {
  if (!rangeTime.value) {
    rangeTime.value = ["", ""];
  }
  searchform.rangeTime.value = "(" + rangeTime.value[0] + ")-" + "(" + rangeTime.value[1] + ")";
  let postParams = { user_id: selectedValue,begin_date: rangeTime.value[0], end_date: rangeTime.value[1],key_words: state.params.key_words, ...params, ...{ logType: logType.value } };
  state.params = postParams;
};
const rangeTime = ref(["", ""]);
// 高级搜索
// 高级搜索表单
const searchFormRef = ref<FormInstance>();
const searchform = reactive({
  employee_name: {
    label: "姓名",
    value: ""
  },
  job_number: {
    label: "工号",
    value: ""
  },
  rangeTime: {
    label: "时间",
    value: ""
  },
  type: {
    label: "请假类型",
    value: "",
    text: "rewiqruhewqio",
    type: "select",
    options: []
  }
});

// 高级搜索表单验证
const searchformRules = reactive({});

//高级搜索模态
const searchbar = ref();

//触发了快速搜索或者搜索方案
const searchBarPost = params => {
  searchform.employee_name.value = "";
  searchform.job_number.value = "";
  rangeTime.value = [];
  searchform.type.value = "";

  let postParams = { ...params.params, key_words: params.search,user_id: selectedValue};
  state.params = postParams;
};

//点击取消按钮关闭高级搜索模态框
const closeModal = (formEl: FormInstance | undefined) => {
  searchFormRef.value?.resetFields();
  searchbar.value.modalHide();
  searchbar.value.clear();

  searchform.employee_name.value = "";
  searchform.job_number.value = "";
  rangeTime.value = ["", ""];
  searchform.type.value = "";

  state.params = {};
};

//打开搜索方案弹出
const showPlanModal = () => {
  searchbar.value.showPlanModal();
  companyLink();
};

//搜索表单提交
const submitForm = async (formEl: FormInstance | undefined) => {
  search_val.value = "";
  let postParams = {
    begin_date: rangeTime.value[0],
    end_date: rangeTime.value[1],
    employee_name: searchform.employee_name.value,
    job_number: searchform.job_number.value,
    type: searchform.type.value
  };
  state.params = postParams;

  searchbar.value.clear();
  searchbar.value.modalHide();
};

// 日志记录--start

const { recordDetail, getRecord, getUserList, getRouterParams } = useSysLogInit();
const { loadDataStatus, setLoadingShow, setLoadingHide } = useLoading();
const { drawerSysDetail, drawerSetShow } = useDrawerSysDetail();
const { recordLangFn } = useGetRecordFn(proxy);

//获取url

//获取用户信息

const { userListOptions, refreshUserList, filterResultOption, selectedValue, filterMethod } = getUserList();

//按人名过滤回调
const fliterChange = () => {
  dataPost({ user_id: selectedValue });
};

//显示抽屉
const drawerShow = row => {
  drawerSetShow(row, getRecordFn);
};

//获取日志数据
const getRecordFn = (params): void => {
  setLoadingShow();
  getRecord(params).then(res => {
    if (res.code == ResultEnum.SUCCESS) {
      setLoadingHide();
      recordDetail.userInfo = res.data.userInfo;
      recordDetail.records = res.data.records;
    }
  });
};

// 预处理数据，
const preProcessData = data => {
  let langCategory = data.tableName || "table1";
  let action = data.action;
  let isChild = "name" in data ? true : false;
  return recordLangFn[action](data, isChild);
};
// 日志记录--end
onMounted(() => {
  refreshUserList();
});
</script>

<style lang="scss" scoped>
.search_header_slot {
  display: flex;
  gap: 10px;
}
:deep(.sys_log_date) {
  width: 230px;
}
.el-drawer__body {
  display: flex;
  flex-direction: column;
  overflow: hidden;
  .record {
    height: 100px;
    flex: 1;
  }
  .merak_modal_content {
    display: flex;
    flex-direction: column;
    position: relative;
    height: 100%;
  }
  .el-loading-parent--relative {
    position: absolute !important;
    margin-top: 0px !important;
    height: 100% !important;
    background-color: rgba(255, 255, 255, 0) !important;
    width: 100%;
    top: 0px;
    left: 0px;
  }
}
.base_info ul {
  list-style: none;
  padding: 0px;
  margin: 0px;
  li {
    padding: 3px 0px;
    font-size: 14px;
  }
}
.el-drawer .el-drawer__body .el-scrollbar {
  padding-right: 0px !important;
  margin-right: 0px !important;
}
.el-table--default .cell {
  padding: 0px 4px;
}
.el-table_1_column_1 {
  text-align: center !important;
  // border-right: 1px solid #ebeef5 !important;
}
.timeline {
  padding-left: 3px;

  .el-timeline-item {
    padding-bottom: 15px;
  }
  .action-icon {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 2px;
    color: #fff;
    border-radius: 50%;
    background: var(--el-timeline-node-color);
  }
  .el-timeline-item__dot {
    transform: translateX(-18%);
  }
  .el-timeline-item__content {
    padding-top: 1px;
  }
  .el-timeline-item__timestamp {
    margin-top: 3px;
    margin-bottom: 6px;
  }

  .action-icon-update {
    background: #1fbeea;
  }
  .action-icon-plus {
    background: #10cf00;
  }
  .action-icon-delete {
    background: #ea1f1f;
  }
}

:deep(.el-timeline-item__tail) {
  border-left: none !important;
}
:deep(.el-timeline-item__wrapper) {
  padding-left: 21px;
}
</style>